<script lang="ts" setup>
import { AuthenticationQrCodeLogin } from '@vben/common-ui';
import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { reactive, ref, onMounted , onBeforeMount, onBeforeUnmount, type Ref} from 'vue';
import { uctoo_vmc } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
import { $t } from '@vben/locales';
import { notification } from 'ant-design-vue';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { useRouter } from 'vue-router';
import { generateClientId, getDomainName } from '#/utils/common';

defineOptions({ name: 'QrCodeLogin' });
const accessStore = useAccessStore();
const userStore = useUserStore();
const router = useRouter();

const client_id = ref("");
const qrcodeSrc = ref("");
/*
// 客户端ID生成器（带本地存储）
const generateClientId = (): string => {
  const STORAGE_KEY = 'client_id'
  
  // 尝试从本地存储获取
  const storedId = localStorage.getItem(STORAGE_KEY)
  if (storedId) return storedId

  // 生成新的UUID v4
  const newId = crypto.randomUUID()
  localStorage.setItem(STORAGE_KEY, newId)
  return newId
}
*/



// WebSocket消息类型
interface WebSocketMessage {
  type: 'message' | 'system'
  content: string
  timestamp: number
  clientId?: string
}

// 响应式状态
const isConnected: Ref<boolean> = ref(false)
const messageInput: Ref<string> = ref('')
const messages = reactive<string[]>([])
let socket: WebSocket | null = null

// 初始化带ClientID的WebSocket
const initWebSocket = (): void => {
  const clientId = client_id.value
  console.log("initWebSocket");
  console.log(clientId);
  const wsUrl = `wss://${getDomainName()}/ws/auth/qrcodelogin/${encodeURIComponent(clientId)}?client_id=${encodeURIComponent(clientId)}`
  
  socket = new WebSocket(wsUrl)

  socket.onopen = (event: Event) => {
    isConnected.value = true
    console.log('连接建立', event)
    sendSystemMessage('Connection established')
  }

  socket.onmessage = (event: MessageEvent<string>) => {
    try {
      const data = JSON.parse(event.data) as WebSocketMessage
      messages.push(`[${data.type}] ${data.content}`)
      const resData = JSON.parse(data.content);
      // 如果成功获取到 accessToken
      if (resData.access_token) {
        let userInfo: any = null;
        const access_token =  resData.access_token;
        const refresh_token =  resData.refresh_token;
        const user = resData.user
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(access_token);
        accessStore.setRefreshToken(refresh_token);

        userInfo = user;

        userStore.setUserInfo(userInfo);
        // accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          
        }

        localStorage.setItem('accessToken', access_token);

        router.push(userInfo.homePath || DEFAULT_HOME_PATH);

        if (userInfo?.name) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.name}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }


    } catch (error) {
      console.error('消息解析失败', error)
    }
  }

  socket.onerror = (event: Event) => {
    console.error('WebSocket错误:', event)
  }

  socket.onclose = (event: CloseEvent) => {
    isConnected.value = false
    console.log('连接关闭:', event)
    sendSystemMessage('Connection closed')
  }
}

// 发送系统消息（带ClientID）
const sendSystemMessage = (content: string): void => {
  if (!socket || socket.readyState !== WebSocket.OPEN) return
  
  const message: WebSocketMessage = {
    type: 'system',
    content,
    timestamp: Date.now(),
    clientId: client_id.value
  }
  socket.send(JSON.stringify(message))
}

// 发送用户消息
const sendMessage = (): void => {
  const content = messageInput.value.trim()
  if (!content || !socket || socket.readyState !== WebSocket.OPEN) return

  const message: WebSocketMessage = {
    type: 'message',
    content,
    timestamp: Date.now(),
    clientId: client_id.value
  }
  
  socket.send(JSON.stringify(message))
  messages.push(`[发送] ${content}`)
  messageInput.value = ''
}

// 连接管理
const toggleConnection = (): void => {
  isConnected.value ? socket?.close() : initWebSocket()
}
//

onMounted(async () => {
  //建立websocket连接，接收扫码登录结果
  console.log('conMounted');
  console.log(client_id.value);
  await initWebSocket();


});
// 组件卸载时清理
onBeforeUnmount(() => {
  if (socket?.readyState === WebSocket.OPEN) {
    socket.close()
  }
})

onBeforeMount(async () => {
  client_id.value = generateClientId();
  const res = await useAxiosRepo(uctoo_vmc).api().wechatopenCreateLoginQRCode({client_id:client_id.value});
  console.log('onMounted');
  console.log(client_id.value);
  console.log('res', res.response?.data?.loginQrcode);
  qrcodeSrc.value = res.response?.data?.loginQrcode;
  console.log(qrcodeSrc.value);
  //建立websocket连接，接收扫码登录结果
});

</script>

<template>
  <AuthenticationQrCodeLogin :login-path="LOGIN_PATH"
  :client_id=client_id :qrcode-src=qrcodeSrc />
</template>
